import { Generator } from '../generator';
import { Parser } from '../parser';
import { Collections, MongoDb } from '../utils/mongo';

export class Article {
	constructor() {
	}

	public async commit() {
		let collection = MongoDb.getCollection<Article>(Collections.ARTICLES);
		if (this.id === 0) {
			// new
			await collection.countDocuments().then(value => {
				this.id = value + 1;
				collection.insertOne(this);
			});
		} else {
			// update
			await collection.updateOne({id: this.id}, {$set: this}, {upsert: true});
		}
	}

	public getTitle(): string {
		return this.title;
	}

	public renderHtml(): string {
		return (new Generator(new Parser(this.content)).generateHTML());
	}

	public static createArticle(title: string, content: string) {
		let instance = new Article();
		instance.title = title;
		instance.content = content;
		return instance;
	}

	public static async getArticleById(id: number): Promise<Article> {
		return MongoDb.findOne(Collections.ARTICLES, {id: id}, Article);
	}

	public static async getAllArticles(): Promise<Array<Article>> {
		return await MongoDb.getCollection<Article>(Collections.ARTICLES).find().toArray();
	}

	private id = 0;
	private title: string = '';
	private content: string = ''; // -> kb4409 markup
}
